package com.gitbl.webchat.web.control;

import com.gitbl.webchat.message.RoomMessage;
import com.gitbl.webchat.web.webmessage.*;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedList;
import java.util.List;

@RestController
@RequestMapping("/room")
public class RoomController extends BaseController {

    @RequestMapping(value = "/create/{title}",method = RequestMethod.POST)
    public Object create(@PathVariable("title")String title,HttpServletRequest request) {
        WebUser u = getUser(request);
        RoomMessage roomM = roomService.createRoom(title,u.getUsername());
        if(roomM==null){
            return new Message(null, WebError.CREATEFAULT);
        }
        WebRoom wroom = Convert.parse(roomM);
        return new Message(wroom,null);
    }
    @RequestMapping(value = "/query",method = RequestMethod.POST)
    public Object query(HttpServletRequest request) {
        String title = request.getParameter("title");
        List<RoomMessage> rooms = roomService.queryRooms(title);
        if(rooms==null){
            return new Message(null, WebError.QUERYFAULT);
        }
        List<WebRoom> wrooms = new LinkedList<>();
        for (RoomMessage m: rooms
             ) {
            WebRoom wroom = Convert.parse(m);
            wrooms.add(wroom);
        }

        return new Message(wrooms,null);
    }
}
